package view;

import java.io.PrintWriter;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Author;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/Register")
public class RegisterServlet extends Servlet {

	private static final long serialVersionUID = 1L;

	@Override
	void fillGetContent(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
		printForm(out, "", "", "");
	}

	private void printForm(PrintWriter out, String firstName, String lastName, String username) {
		out.println("<form id='registerForm' action='Controller' method='POST'>");

		out.println("	<label for='firstName'>Nome:</label>");
		out.println("	<input id='firstName' type='text' name='firstName' value='" + firstName + "'></br>");
		out.println("	<label for='lastName'>Sobrenome:</label>");
		out.println("	<input id='lastName' type='text' name='lastName' value='" + lastName + "'></br>");

		out.println("	<label for='username'>Username:</label>");
		out.println("	<input id='username' type='text' name='username' value='" + username + "'></br>");

		out.println("	<label for='password'>Senha:</label>");
		out.println("	<input id='password' type='password' name='password'></br>");
		out.println("	<label for='confirmPassword'>Confirmar Senha:</label>");
		out.println("	<input id='confirmPassword' type='password' name='confirmPassword'></br>");

		out.println("	<input type='submit' name='button' value='Registrar' style='margin-left:228px;'>");

		out.println("</form>");
	}

	@Override
	void fillPostContent(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
		String firstName = request.getParameter("firstName");
		String lastName = request.getParameter("lastName");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String confirmPassword = request.getParameter("confirmPassword");

		try {
			if (password.equals(confirmPassword)) {
				Author author = new Author(firstName, lastName, username, password);
				author.register();

				out.println(HtmlFactory.createSuccessMessage("Seja bem-vindo(a), " + firstName
						+ "! Seu cadastro foi realizado com sucesso!"));
			} else {
				throw new Exception("As senhas não são iguais!");
			}
		} catch (Exception e) {
			out.println(HtmlFactory.createErrorMessage(e.getMessage()));
			printForm(out, firstName, lastName, username);
		}
	}
}
